import { defineComponent } from 'vue';
import type { PopoverAction } from 'vant';
import { Popover } from 'vant';
import { includes } from 'lodash-es';
import setting from '/@/settings/projectSetting';
import { Icon } from '/@/components/Icon';
import { aTabClick, awaitWrap } from '/@/utils';
import { ExportDeckImgApi } from '/@/api/currentDeck/deck';
import { useMessage } from '/@/hooks/web/useMessage';

const UseExport = defineComponent({
  name: 'UseExport',
  props: {
    deckId: {
      type: String as PropType<string>,
      required: true,
    },
    gameId: {
      type: String as PropType<string>,
      default: () => {
        return '';
      },
    },
  },
  setup(props) {
    const { createLoadingToast, clearToast, createInfoToast } = useMessage();

    const actionArray: PopoverAction[] = [{ text: '大图' }, { text: '小图' }]; // , { text: 'PDF' };
    const game_id = props.gameId!;
    if (includes(setting.DeckConfig.matchSheet, game_id)) {
      actionArray.push({ text: '赛用' });
    }

    // 导出图片
    const downLoadImageClick = async (type = 0) => {
      createLoadingToast({
        message: '生成图片中',
        overlay: true,
      });
      const [error, data] = await awaitWrap(ExportDeckImgApi({ deck_id: Number(props.deckId), type: type }));
      if (error) {
        clearToast();
        return;
      }
      clearToast();
      if (!data) {
        createInfoToast({ message: '图片正在生成中，稍后请再次点击导出', overlay: true });
        return;
      }
      aTabClick(data!, '_blank');
    };

    // @ts-ignore
    const ExportPopoverSelect = (item: PopoverAction, index: number) => {
      switch (index) {
        case 0:
          downLoadImageClick();
          break;
        case 1:
          downLoadImageClick(1);
          break;
        case 2:
          downLoadImageClick(2);
          break;
      }
    };

    const popoverSlot = {
      reference: () => {
        return (
          <div class={'exprot flex flex-col items-center'}>
            <Icon class={'!text-xl mb-sm'} icon={'bi:image'} />
            <span>导出</span>
          </div>
        );
      },
    };
    return () => (
      <Popover actions={actionArray} placement={'top-start'} v-slots={popoverSlot} onSelect={ExportPopoverSelect} />
    );
  },
});

export const useExportHooks = () => {
  return { UseExport };
};
